import BaseModel from './BaseModel';
import makeRequest from '../request/request';
import { AddressData } from './data/AddressData';

export default class AddressModel extends BaseModel<any> {
	constructor(deviceData : Partial<AddressData> = {}) {
		super('/unapp/userAddress', 'AddressModel');  // 设置基础路径和缓存键
		Object.assign(this, new AddressData(deviceData));
	}

	/**
	 * 获取地址列表
	 * @returns 地址列表
	 */
	async getList(page : number) : Promise<AddressData[]> {
		const response = await makeRequest({
			url: `${this.endpoint}/getAll`,
			method: 'GET',
			data: { page },
			hideLoading: true,
		});
		const dataList = response.data.map((item : Partial<AddressData>) => {
			return new AddressData(item);
		});
		return dataList;
	}

	/**
	 * 创建收货地址
	 * @returns 创建收货地址
	 */
	async getDetail(id : string) : Promise<any> {
		const response = await makeRequest({
			url: `${this.endpoint}/getById`,
			method: 'POST',
			data: { id },
		});
		// 使用类型断言来确保返回的数据符合 OrderData
		return response.data;
	}


	/**
	 * 创建收货地址
	 * @returns 创建收货地址
	 */
	async updateDetail(model : AddressData) : Promise<any> {
		let url = 'add';
		if (model) {
			if (model.id) url = 'update';
		}
		const response = await makeRequest({
			url: `${this.endpoint}/${url}`,
			method: 'POST',
			data: model,
		});
		// 使用类型断言来确保返回的数据符合 OrderData
		return response.data;
	}

	async setDefault(id : number) : Promise<any> {
		const response = await makeRequest({
			url: `${this.endpoint}/setDefaultAddress`,
			method: 'POST',
			data: { id }
		});
		// 使用类型断言来确保返回的数据符合 OrderData
		return response.data;
	}

	async delete(id : number) : Promise<any> {
		const response = await makeRequest({
			url: `${this.endpoint}/delById`,
			method: 'DELETE',
			data: { id },
			query: true,
		});
		// 使用类型断言来确保返回的数据符合 OrderData
		return response.data;
	}
}